<template>
    <div class="tabbar">
        <van-tabbar v-model="active">
            <van-tabbar-item v-for="i in tabbarData" :badge="parseInt(i.badge)>99?'99':i.badge" :key="i" :name="i.path" :icon="i.icon" :to="i.path">{{i.title}}</van-tabbar-item>
        </van-tabbar>
    </div>
</template>

<script lang="ts" setup>
  import { ref,reactive,inject,watch} from 'vue'
  import { Tabbar, TabbarItem } from 'vant';
  import { useRouter } from "vue-router";
  import { useStore } from 'vuex'
  import {initWebSocket,webscoketDealData} from '../../utils/websocket.js'
  import formatTime from '../../utils/time.js'
  const store = useStore();
  const router = useRouter();
  const messageCount = ref(0)

  const tabbarData = reactive([{
      icon:'home-o',
      title:'职位',
      path:'/home/index',
      badge:''
  },{
      icon:'chat-o',
      title:'消息',
      path:'/home/message',
      badge: ''
  },{
      icon:'contact',
      title:'我的',
      path:'/home/mine',
      badge:''
  }
  ])
  const active = ref('/home/index');
  active.value = router.currentRoute.value.path


  let user = JSON.parse(localStorage.getItem('user'))
  const token = localStorage.getItem('user_token')
  const global:String = inject('global')
  const WebSocketUrl = ref(global?.ws+'/chatserver/user/'+user.id+'/'+token)

  const messagesList = ref([])

  //判断时间是否是昨天
  const setTime = (time)=>{
    let date = new Date(time);
    let time1 = ''
    switch(formatTime.isToday(time)){
      case '今天':
      time1 = formatTime.format(date,'hh:mm')
      break;
      case '昨天':
      time1 = '昨天'
      break;
      default:
        console.log('时间' + formatTime.isToday(time))
    }
    return time1
  }

  const websocket = initWebSocket(WebSocketUrl.value)

  //接收消息
  websocket.onmessage = (res)=>{
    tabbarData[1].badge = ++messageCount.value;
    let data = JSON.parse(res.data)
    data.time = setTime(data.time)
    if(messagesList?.value.length){
      let index = messagesList.value.findIndex((val,index,arr)=>{
        return val.from.id == data.from.id;
      })
      if(index!=-1){
        let count  = messagesList.value[index].msgCount
        messagesList.value[index] = data
        messagesList.value[index].msgCount = count + 1;
      }else{
        data.msgCount = 1;
        messagesList.value.push(data)
      }
    }else{
      data.msgCount = 1;
      messagesList?.value.push(data)
    }
    store.commit("setMessageList", messagesList?.value);
  }
  

</script>

<style lang="scss">
.tabbar{

}
</style>
